﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LeoShi.Soft.OpenSinaAPI;
using System.Web;
using System.Net;
using System.Configuration;
using System.IO;
using System.Xml;

namespace Windvoice.Authorize
{
    public class SinaConnector
    {
        public static string GetRequestToken()
        {
            var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.GET) as HttpGet;
            httpRequest.GetRequestToken();
            string url = httpRequest.GetAuthorizationUrl();
            HttpContext.Current.Session["oauth_token"] = httpRequest.Token;
            HttpContext.Current.Session["oauth_token_secret"] = httpRequest.TokenSecret;

            return url;
        }

        public static void GetAccessToken()
        {
            var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.GET) as HttpGet;
            if (HttpContext.Current.Request["oauth_verifier"] != null)
            {
                httpRequest.Token = HttpContext.Current.Session["oauth_token"].ToString();
                httpRequest.TokenSecret = HttpContext.Current.Session["oauth_token_secret"].ToString();
                httpRequest.Verifier = HttpContext.Current.Request["oauth_verifier"];
                httpRequest.GetAccessToken();
                HttpContext.Current.Session["oauth_token"] = httpRequest.Token;
                HttpContext.Current.Session["oauth_token_secret"] = httpRequest.TokenSecret;

                GetUser();
            }
            else
            {
                throw new Exception("啊哦，看来新浪抽风了，连不上啊！");
            }
        }

        private static void GetUser()
        {
            oAuthBase oAuth = new oAuthBase();
            Uri uri = new Uri("http://api.t.sina.com.cn/account/verify_credentials.xml");
            string nonce = oAuth.GenerateNonce();
            string timeStamp = oAuth.GenerateTimeStamp();
            string normalizeUrl, normalizedRequestParameters;
            // 签名
            string sig = oAuth.GenerateSignature(
            uri,
            ConfigurationManager.AppSettings["app_key"],
            ConfigurationManager.AppSettings["app_secret"],
            HttpContext.Current.Session["oauth_token"].ToString(),
            HttpContext.Current.Session["oauth_token_secret"].ToString(),
            "Get",
            timeStamp,
            nonce,
            out normalizeUrl,
            out normalizedRequestParameters);
            sig = HttpUtility.UrlEncode(sig);
            StringBuilder sb = new StringBuilder(uri.ToString());
            sb.AppendFormat("?oauth_consumer_key={0}&", ConfigurationManager.AppSettings["app_key"]);
            sb.AppendFormat("oauth_nonce={0}&", nonce);
            sb.AppendFormat("oauth_timestamp={0}&", timeStamp);
            sb.AppendFormat("oauth_signature_method={0}&", "HMAC-SHA1");
            sb.AppendFormat("oauth_version={0}&", "1.0");
            sb.AppendFormat("oauth_signature={0}&", sig);
            sb.AppendFormat("oauth_token={0}&", HttpContext.Current.Session["oauth_token"].ToString());
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sb.ToString());
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader stream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
            string responseBody = stream.ReadToEnd();
            stream.Close();
            response.Close();

            XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml(responseBody);

            User user = new User();
            user.Description = xdoc.SelectSingleNode("/user/description").InnerText;
            user.DisplayName = xdoc.SelectSingleNode("/user/screen_name").InnerText;
            user.Gender = xdoc.SelectSingleNode("/user/gender").InnerText == "m" ? 1 : 0;
            user.Location = xdoc.SelectSingleNode("/user/location").InnerText;
            user.PortraitUrl = xdoc.SelectSingleNode("/user/profile_image_url").InnerText;
            user.Source = (int)UserSource.Sina;
            user.UniqueID = Convert.ToInt64(xdoc.SelectSingleNode("/user/id").InnerText);
            user.Url = xdoc.SelectSingleNode("/user/url").InnerText;
            user.Domain = xdoc.SelectSingleNode("/user/domain").InnerText;
            user.Verified = xdoc.SelectSingleNode("/user/verified").InnerText == "true" ? true : false;

            var query = from u in User.FindAll() where u.Source == user.Source && u.UniqueID == user.UniqueID select u;
            if (query.Count() != 1)
                user.Save();
            else
                user.ID = User.FindAll().Where(u => u.UniqueID == user.UniqueID && u.Source == user.Source).Single().ID;

            HttpContext.Current.Session["user"] = user;
        }

    }
}
